package com.whitedust.top30;

import com.whitedust.structure.ListNode;

import java.util.List;

/**
 * @author A
 * @since 2025/11/3 19:15
 */

public class Top29 {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headB == null || headA == null) return null;
        int lenA = 0;
        int lenB = 0;
        ListNode A = headA;
        ListNode B = headB;
        while (A != null) {
            lenA++;
            A = A.next;
        }
        while (B != null) {
            lenB++;
            B = B.next;
        }
        if (lenA > lenB) {
            for (int i = 0; i < lenA - lenB; i++) {
                headA = headA.next;
            }
        } else {
            for (int i = 0; i < lenB - lenA; i++) {
                headB = headB.next;
            }
        }
        while (headA != null) {
            if (headB == headA) return headA;
            headA = headA.next;
            headB = headB.next;
        }
        return null;
    }
}
